var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../../common/common');
var DBConfig = require('../../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);


// 获取购物车列表 3
router.get('/jkyx/cart_list', function(req, res, next) {
	var param = req.query || req.params; 
	var account_id = param.account_id;
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.getCartList,[account_id],function (err, results) {
			connection.release();
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				getCartList(results,res)
//				res.end(JSON.stringify({
//	     			msg: '操作成功',
//	     			status:'100',
//	     			results: results
//	     		}));	         
			}
		})
	})
});
// 购物车增加商品 一次数量变化1个
router.get('/jkyx/cart_add', function(req, res, next) {
	var param = req.query || req.params; 
	// 用户account_id
	var account_id = param.account_id || '';
	// 商品ID
	var goods_id = param.goods_id || '';
	// 商品的规格ID
	var spec_id = param.spec_id || '';
	// 商品的数量
	var spec_num = param.spec_num || 1;
	if (account_id == '' || goods_id == '' || spec_id == '') {
		res.end(JSON.stringify({
 			msg: '请传入正确的参数',
 			status:'105',
 		}));
 		return;
	}
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.getCartList,[account_id],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				// 购物车为空
				if (results.length == 0) {
					connection.query(DBConfig.insertCart,[account_id,goods_id,spec_id,spec_num,'1',CommonJS.getNowFormatDate(),account_id],function (err, results) {
						connection.release();
						if (err){
						  	res.end(JSON.stringify({
				     			msg: '数据库查询失败',
				     			status:'103',
				     			err: err
				     		}));
						}else{
							var retGoods = results[1];
							getCartList(retGoods,res,spec_id);
						}
					})
				} else{ // 购物车  非空
					var resCart = results;
					var cartGoods_len = resCart.length;
					var is_same = 1;
					// 商品ID相同，规格相同
					for (var i = 0; i < cartGoods_len; i ++) {
						if (resCart[i].goods_id == goods_id && resCart[i].spec_id == spec_id) {
							var num = resCart[i].num + 1;
							var id = resCart[i].id;
							is_same = 2; 
							connection.query(DBConfig.updateCart,[num,id,account_id],function (err, results) {
								connection.release();
								if (err){
								  	res.end(JSON.stringify({
						     			msg: '数据库查询失败',
						     			status:'102',
						     			err: err
						     		}));
								}else{
									var retGoods = results[1];
									getCartList(retGoods,res);
								}
							})
						}
					}
					// 规格或者商品 ID  不同  就当一条新的记录
					if (is_same == 1) {
						connection.query(DBConfig.insertCart,[account_id,goods_id,spec_id,spec_num,'1',CommonJS.getNowFormatDate(),account_id],function (err, results) {
							connection.release();
							if (err){
							  	res.end(JSON.stringify({
					     			msg: '数据库查询失败',
					     			status:'102',
					     			err: err
					     		}));
							}else{
								var retGoods = results[1];
								getCartList(retGoods,res);
							}
						})
					}
				}   
			}
		})
	})
});

// 购物车减少商品 一次数量变化1个
router.get('/jkyx/cart_reduce', function(req, res, next) {
	var param = req.query || req.params; 
	// 用户account_id
	var account_id = param.account_id || '';
	// 商品ID
	var goods_id = param.goods_id || '';
	// 商品的规格ID
	var spec_id = param.spec_id || '';
	if (account_id == '' || goods_id == '' || spec_id == '') {
		res.end(JSON.stringify({
 			msg: '请传入正确的参数',
 			status:'105',
 		}));
 		return;
	}
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.getCartOneList,[account_id,goods_id,spec_id],function (err, results) {
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				var resCart = results[0];
				var num = resCart.num - 1;
				var id = resCart.id;
				// 删除
				if (num == 0) {
					connection.query(DBConfig.delectOndCartList,[id,account_id],function (err, results) {
						connection.release();
						if (err){
						  	res.end(JSON.stringify({
				     			msg: '数据库查询失败',
				     			status:'102',
				     			err: err
				     		}));
						}else{
							var retGoods = results[1];
							getCartList(retGoods,res);
						}
					})	
				} else{  // 减1
					connection.query(DBConfig.updateCart,[num,id,account_id],function (err, results) {
						connection.release();
						if (err){
						  	res.end(JSON.stringify({
				     			msg: '数据库查询失败',
				     			status:'102',
				     			err: err
				     		}));
						}else{
							var retGoods = results[1];
							getCartList(retGoods,res);
						}
					})	
				}
			}
		})
	})
});
// 购物车删除商品 
router.get('/jkyx/cart_delete', function(req, res, next) {
	var param = req.query || req.params; 
	// 用户account_id
	var account_id = param.account_id || '';
	// 商品ID
	var goods_id = param.goods_id || '';
	// 商品的规格ID
	var spec_id = param.spec_id || '';
	if (account_id == '' || goods_id == '' || spec_id == '') {
		res.end(JSON.stringify({
 			msg: '请传入正确的参数',
 			status:'105',
 		}));
 		return;
	}
    pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}
		connection.query(DBConfig.delectOndCartList2,[account_id,goods_id,spec_id,account_id],function (err, results) {
			connection.release();
			if (err){
			  	res.end(JSON.stringify({
	     			msg: '数据库查询失败',
	     			status:'102',
	     			err: err
	     		}));
			}else{
				var retGoods = results[1];
				getCartList(retGoods,res);
			}
		})
	})
});


// 获取购物车中的商品列表
function getCartList(retGoods,res,spec_id){
	if (retGoods.length == 0) {
		res.end(JSON.stringify({
 			msg: '操作成功',
 			status:'100',
 			carts: [],
 		}));	  
 		return;
	}
	// 处理商品
	var goodsIDS = ''; // 商品IDs
	var specIDS = ''; // 规格
	var subLen = retGoods.length;
	for (var j = 0; j < subLen; j ++) {
		goodsIDS = goodsIDS + retGoods[j].goods_id + ',';
		specIDS = specIDS + retGoods[j].spec_id + ',';
	} 
	// 去掉最后一个','
	goodsIDS = goodsIDS.substring(0,(goodsIDS.length - 1)); 
	specIDS = specIDS.substring(0,(specIDS.length - 1));
	var selGoods = 'select * from goods where id in (' + goodsIDS + '); select * from goods_spec where id in (' + specIDS + ');';
	pool.getConnection(function(err, connection) {
		if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101',
     		}));
		}else{
			connection.query(selGoods,function (err, results) {
				connection.release();
				if (err){
				  	res.end(JSON.stringify({
		     			msg: '数据库查询失败',
		     			status:'103',
		     			err: err
		     		}));
				}else{
					// 处理商品
					var cartGoods = results[0];
					var cartGoods_len = cartGoods.length;
					// 加规格
					var cartSpecs = results[1];
					var cartSpecs_len = cartSpecs.length;
					var tempGoods = [];
					// 循环遍历 购物车中的记录
					for (var i = 0; i < subLen; i ++) {
						var good = getGoods(cartGoods,retGoods[i].goods_id);
						var spec = getSpecs(cartSpecs,retGoods[i].spec_id);
						var num = retGoods[i].num;
						var cart_id = retGoods[i].id;
						var item = {
							id: good.id, // 商品ID
							name: good.name, // 商品名字
							descr: good.descr, // 商品描述
							imgs: good.imgs, // 商品轮播图
							detail_imgs: good.detail_imgs, // 商品详细
							pre_sale_time: good.pre_sale_time, // 预售时间
							spec: {
								id: spec.id,  // 规格ID
								price: spec.price, // 价格
								origprice: spec.origprice, // 原价
								spec: spec.spec, // 规格
								salecount: spec.salecount,  // 销量
								stock: spec.stock, // 库存
							},
							num: num,  // 商品数量
							cart_id: cart_id
						}
						tempGoods.push(item);
					}
					res.end(JSON.stringify({
		     			msg: '操作成功',
		     			status:'100',
		     			carts: tempGoods,
		     		}));	  
				}
			})
		}
	})
}
// 根据商品 ID  寻找商品数组中的商品
// goods: 商品数组
// goods_id: 商品ID
function getGoods(goods,goods_id){
	var len = goods.length;
	for (var i = 0; i < len; i ++) {
		if (goods[i].id == goods_id) {
			if (typeof goods[i].imgs === 'string') {
				goods[i].imgs = JSON.parse(goods[i].imgs);
			}
			return goods[i];
		}
	}
	return false;
}
// 根据规格ID 寻找规格数组中的规格
// specs: 规格数组
// spec_id: 规格ID
function getSpecs(specs,spec_id){
	var len = specs.length;
	for (var i = 0; i < len; i ++) {
		if (specs[i].id == spec_id) {
			return specs[i];
		}
	}
	return false;
}

module.exports = router;
